package cyan.gf.sql;

import cyan.gf.control.SimpleTreeItem;
import cyan.gf.db.CrudInstance;
import cyan.gf.db.TableField;
import cyan.gf.field.FieldWarpper;
import cyan.gf.field.MySQLFieldWarpper;
import cyan.gf.tree.TreeLeaf;
import javafx.scene.control.TreeItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cyan on 2017/3/3.
 * Email:qsyan@vip.qq.com
 */
public class MySQLDao {

  CrudInstance crudInstance;

  public MySQLDao(CrudInstance crudInstance) {
    this.crudInstance = crudInstance;
  }

  public List<TreeItem<SimpleTreeItem>> loadTables(String schemaName) {
    List<TreeItem<SimpleTreeItem>> treeItems = new ArrayList<>();
    String query = String.format("select TABLE_NAME from information_schema.TABLES WHERE TABLE_SCHEMA='%s'", schemaName);
    crudInstance.eachRow(query, rs -> {
      SimpleTreeItem simpleTreeItem = new SimpleTreeItem(rs.getString(1), "/images/tree_table.png");
      simpleTreeItem.setMessage(TreeLeaf.TABLE);
      treeItems.add(new TreeItem<>(simpleTreeItem));
    });
    return treeItems;
  }

  public List<TableField> getTableFields(String currentSchemaName, String currentTableName) {
    String query = String.format("show full fields from %s.%s", currentSchemaName, currentTableName);
    List<TableField> tableFields = new ArrayList<>();
    FieldWarpper fieldWarpper = new MySQLFieldWarpper();
    crudInstance.eachRow(query, row -> tableFields.add(fieldWarpper.warpperd(row)));
    return tableFields;
  }

  public List<TreeItem<SimpleTreeItem>> listSchema() {
    String query = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA";
    List<TreeItem<SimpleTreeItem>> treeItems = new ArrayList<>();
    crudInstance.eachRow(query, row -> {
      SimpleTreeItem simpleTreeItem = new SimpleTreeItem(row.getString(1), "/images/tree_schema.png");
      simpleTreeItem.setMessage(TreeLeaf.SCHEMA);
      treeItems.add(new TreeItem<>(simpleTreeItem));
    });
    return treeItems;
  }
}
